package com.example.idlefish.HomeAndSearch

import SearchHistoryManager
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.R
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class ButtonSheetHistoryFragment : BottomSheetDialogFragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.bottom_sheet_history_layout, container, false)
    }

    override fun onStart() {
        super.onStart()
        dialog?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)?.let { bottomSheet ->
            val behavior = BottomSheetBehavior.from(bottomSheet)
            bottomSheet.layoutParams.height = (resources.displayMetrics.heightPixels * 0.8).toInt() // 设置高度为屏幕的 80%
            behavior.state = BottomSheetBehavior.STATE_EXPANDED // 设置为展开状态
            bottomSheet.requestLayout() // 强制重新布局
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //val originalBitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_search_delete)
        //val scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, 50, 50, true)

        // 设置缩放后的图片到 del_button
        //val delButton = view.findViewById<ImageButton>(R.id.del_button)
            //delButton.setImageBitmap(scaledBitmap)
        dialog?.setOnShowListener { dialogInterface ->
            val bottomSheet = (dialogInterface as BottomSheetDialog).findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            val behavior = BottomSheetBehavior.from(bottomSheet!!)
            bottomSheet.layoutParams.height = (resources.displayMetrics.heightPixels * 0.8).toInt()
            behavior.state = BottomSheetBehavior.STATE_EXPANDED // 设置为展开状态
            bottomSheet.requestLayout()
        }
        val searchHistoryManager = SearchHistoryManager(requireContext())
        var history = searchHistoryManager.loadSearchHistory()
        println(history)
        val historylist= view.findViewById<RecyclerView>(R.id.his_item)
        historylist.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        val adapter_type = HistoryItemAdapter(history, { data ->
            val currentText = data
            val intent = Intent(requireContext(), OneResultActivity::class.java)
            intent.putExtra("name", currentText) // 传入键值对
            intent.putExtra("type", "0")
            startActivity(intent)
            val searchHistoryManager = SearchHistoryManager(requireContext())
            // 添加搜索记录
            searchHistoryManager.saveSearchRecord(currentText)
        }, historylist, requireContext())
        historylist.adapter = adapter_type

        historylist.post {
            dialog?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)?.let { bottomSheet ->
                val behavior = BottomSheetBehavior.from(bottomSheet)
                bottomSheet.layoutParams.height = (resources.displayMetrics.heightPixels * 0.8).toInt()
                behavior.state = BottomSheetBehavior.STATE_EXPANDED
                bottomSheet.requestLayout()
            }
        }

        val num = view.findViewById<TextView>(R.id.num)
        val n = searchHistoryManager.loadSearchHistory().size
        num.text = "共有"+n.toString()+ "条记录"


         val del_button =view.findViewById<LinearLayout>(R.id.clearall)
         del_button.setOnClickListener {
             // 构建一个弹窗
             AlertDialog.Builder(requireContext())
                 .setTitle("确认删除") // 弹窗标题
                 .setMessage("确定要删除所有历史记录吗？") // 弹窗内容
                 .setPositiveButton("确定") { dialog, which ->
                     // 点击“确定”按钮的操作
                     // 清空历史记录
                    searchHistoryManager.clearSearchHistory()
                     history.clear()
                     historylist.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
                     val adapter_type = HistoryItemAdapter(history.toMutableList(), { selectedItem ->
                         println("Clicked item: $selectedItem")
                     }, historylist, requireContext())
                     historylist.adapter = adapter_type

                    println("历史记录已删除")
                }
                .setNegativeButton("取消") { dialog, which ->
                    // 点击“取消”按钮的操作
                    println("取消删除操作")
                }
                .create()
                .show()
        }


        //dismiss() // 关闭弹窗
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        // 通知父 Activity，BottomSheet 已经被关闭
        parentFragmentManager.setFragmentResult("BottomSheetDismissed", Bundle())
    }
}
